package classfile

import "encoding/binary"

type ClassReader struct {
	data []uint8
	pos  uint32
}

func (self *ClassReader) SetData(data []uint8) ClassReader {
	self.data = data
	self.pos = 0
	return *self
}

func (self *ClassReader) GetPos() uint32 {
	return self.pos
}

// 读取1个字节，剪掉已读的1个字节并返回
func (cr *ClassReader) ReadUInt8() uint8 {
	val := cr.data[cr.pos]
	cr.pos += 1
	return val
}

// 2个字节(大端读)
func (cr *ClassReader) ReadUInt16() uint16 {
	val := binary.BigEndian.Uint16(cr.ReadBytes(2))
	return val
}

// 4个字节
func (cr *ClassReader) ReadUInt32() uint32 {
	val := binary.BigEndian.Uint32(cr.ReadBytes(4))
	return val
}

// 8个字节
func (cr *ClassReader) ReadUInt64() uint64 {
	val := binary.BigEndian.Uint64(cr.ReadBytes(8))
	return val
}

// 读取uint16表
func (cr *ClassReader) ReadUInt16s() []uint16 {
	n := cr.ReadUInt16()
	s := make([]uint16, n)
	for i := range s {
		s[i] = cr.ReadUInt16()
	}
	return s
}

// 读取指定数量的字节
func (cr *ClassReader) ReadBytes(n uint32) []byte {
	bytes := cr.data[cr.pos : cr.pos+n]
	cr.pos += n
	return bytes
}
